const { ipcRenderer } = require('electron');

// 获取DOM元素
const reportTypeButtons = document.querySelectorAll('.report-type-btn');
const reportForm = document.getElementById('report-form');
const statusGroup = document.getElementById('status-group');
const dateGroup = document.getElementById('date-group');
const dateRangeGroup = document.getElementById('date-range-group');
const generatePreviewBtn = document.getElementById('generate-preview-btn');
const exportTextBtn = document.getElementById('export-text-btn');
const exportMdBtn = document.getElementById('export-md-btn');
const copyReportBtn = document.getElementById('copy-report-btn');
const reportPreview = document.getElementById('report-preview');
const previewContent = document.getElementById('preview-content');
const closePreviewBtn = document.getElementById('close-preview-btn');
const closeReportBtn = document.getElementById('close-report-generator');

// 当前报告类型
let currentReportType = 'daily';
// 原始任务数据
let allTasks = [];

// 初始化
window.addEventListener('DOMContentLoaded', () => {
    // 设置默认日期
    const today = new Date();
    const formattedDate = today.toISOString().split('T')[0];
    document.getElementById('report-date').value = formattedDate;
    
    // 设置默认日期范围（周报用）
    const startDate = new Date(today);
    startDate.setDate(today.getDate() - 7);
    document.getElementById('report-start-date').value = startDate.toISOString().split('T')[0];
    document.getElementById('report-end-date').value = formattedDate;
    
    // 监听日期变化事件
    document.getElementById('report-date').addEventListener('change', updateTaskList);
    document.getElementById('report-start-date').addEventListener('change', updateTaskList);
    document.getElementById('report-end-date').addEventListener('change', updateTaskList);
    
    // 尝试从localStorage加载个人信息
    loadUserInfoFromSettings();
    
    // 请求获取用户信息和任务数据
    ipcRenderer.send('get-report-data');
});

// 加载用户信息
function loadUserInfoFromSettings() {
    try {
        const settings = JSON.parse(localStorage.getItem('widgetSettings'));
        if (settings && settings.shareInfo) {
            document.getElementById('report-name').value = settings.shareInfo.name || '';
            document.getElementById('report-department').value = settings.shareInfo.department || '';
            document.getElementById('report-position').value = settings.shareInfo.position || '';
        }
    } catch (error) {
        console.error('加载用户信息失败:', error);
    }
}

// 转换状态为中文
function getStatusText(status) {
    const statusMap = {
        'pending': '待办',
        'in-progress': '进行中',
        'completed': '已完成'
    };
    return statusMap[status] || status;
}

// 转换优先级为中文
function getPriorityText(priority) {
    const priorityMap = {
        'low': '低',
        'medium': '中',
        'high': '高'
    };
    return priorityMap[priority] || priority;
}

// 监听从主进程发送的数据
ipcRenderer.on('report-data', (event, data) => {
    // 先尝试从localStorage加载用户信息，确保获取最新的设置
    loadUserInfoFromSettings();
    
    // 如果主进程提供了用户信息，也进行填充（优先级低于localStorage）
    if (data.userInfo && (!document.getElementById('report-name').value || 
                         !document.getElementById('report-department').value || 
                         !document.getElementById('report-position').value)) {
        document.getElementById('report-name').value = document.getElementById('report-name').value || data.userInfo.name || '';
        document.getElementById('report-department').value = document.getElementById('report-department').value || data.userInfo.department || '';
        document.getElementById('report-position').value = document.getElementById('report-position').value || data.userInfo.position || '';
    }
    
    // 填充状态信息
    if (data.status) {
        document.getElementById('report-status').value = data.status.name || '';
    }
    
    // 设置报告类型（如果有）
    if (data.reportType) {
        currentReportType = data.reportType;
        
        // 更新按钮选中状态
        reportTypeButtons.forEach(btn => {
            if (btn.dataset.type === currentReportType) {
                btn.classList.add('active');
            } else {
                btn.classList.remove('active');
            }
        });
        
        updateFormFields();
    }
    
    // 保存原始任务数据
    if (data.tasks) {
        allTasks = data.tasks;
        updateTaskList();
    }
});

// 根据报告类型和日期范围筛选任务
function filterTasksByDateRange(tasks, reportType, date, startDate, endDate) {
    if (!tasks || tasks.length === 0) return [];
    
    const filteredTasks = [];
    
    // 转换日期字符串为Date对象
    const dateObj = date ? new Date(date) : new Date();
    const startDateObj = startDate ? new Date(startDate) : null;
    const endDateObj = endDate ? new Date(endDate) : null;
    
    tasks.forEach(task => {
        // 假设任务有created_at字段表示创建日期
        const taskDate = task.created_at ? new Date(task.created_at) : new Date();
        
        // 根据报告类型筛选
        if (reportType === 'daily') {
            // 日报：只显示当天的任务
            if (isSameDay(taskDate, dateObj)) {
                filteredTasks.push(task);
            }
        } else if (reportType === 'weekly') {
            // 周报：显示指定日期范围内的任务
            if (startDateObj && endDateObj && taskDate >= startDateObj && taskDate <= endDateObj) {
                filteredTasks.push(task);
            }
        } else if (reportType === 'monthly') {
            // 月报：显示当月的任务
            if (isSameMonth(taskDate, dateObj)) {
                filteredTasks.push(task);
            }
        }
    });
    
    return filteredTasks;
}

// 判断两个日期是否是同一天
function isSameDay(date1, date2) {
    return date1.getFullYear() === date2.getFullYear() &&
           date1.getMonth() === date2.getMonth() &&
           date1.getDate() === date2.getDate();
}

// 判断两个日期是否是同一个月
function isSameMonth(date1, date2) {
    return date1.getFullYear() === date2.getFullYear() &&
           date1.getMonth() === date2.getMonth();
}

// 更新任务列表显示
function updateTaskList() {
    const date = document.getElementById('report-date').value;
    const startDate = document.getElementById('report-start-date').value;
    const endDate = document.getElementById('report-end-date').value;
    
    // 根据报告类型和日期范围筛选任务
    const filteredTasks = filterTasksByDateRange(allTasks, currentReportType, date, startDate, endDate);
    
    // 更新任务文本域，包含优先级、状态和工时信息
    const tasksText = filteredTasks.map(task => {
        const statusText = getStatusText(task.status);
        const priorityText = getPriorityText(task.priority);
        const hoursText = task.hours && task.hours > 0 ? ` [工时: ${task.hours}小时]` : '';
        return `- ${task.title} [${statusText}] [优先级: ${priorityText}]${hoursText}`;
    }).join('\n');
    document.getElementById('report-tasks').value = tasksText;
}

// 切换报告类型
reportTypeButtons.forEach(button => {
    button.addEventListener('click', () => {
        // 更新活动按钮
        reportTypeButtons.forEach(btn => btn.classList.remove('active'));
        button.classList.add('active');
        
        // 更新当前报告类型
        currentReportType = button.dataset.type;
        
        // 根据报告类型显示/隐藏相关字段
        updateFormFields();
        
        // 更新任务列表，显示对应时间范围内的任务
        updateTaskList();
    });
});

// 更新表单字段显示
function updateFormFields() {
    // 显示/隐藏状态字段
    statusGroup.style.display = currentReportType === 'daily' ? 'block' : 'none';
    
    // 显示/隐藏日期字段
    dateGroup.style.display = currentReportType === 'daily' ? 'block' : 'none';
    
    // 显示/隐藏日期范围字段
    dateRangeGroup.style.display = currentReportType === 'weekly' ? 'block' : 'none';
    
    // 显示/隐藏工作成果字段
    document.getElementById('report-achievements').closest('.form-group').style.display = 
        currentReportType === 'monthly' ? 'block' : 'none';
}

// 生成报告预览
generatePreviewBtn.addEventListener('click', () => {
    const reportData = getReportData();
    let reportContent = '';
    
    // 根据报告类型生成内容
    if (currentReportType === 'daily') {
        reportContent = generateDailyReport(reportData);
    } else if (currentReportType === 'weekly') {
        reportContent = generateWeeklyReport(reportData);
    } else if (currentReportType === 'monthly') {
        reportContent = generateMonthlyReport(reportData);
    }
    
    // 显示预览
    previewContent.textContent = reportContent;
    reportPreview.style.display = 'block';
    
    // 滚动到预览区域
    reportPreview.scrollIntoView({ behavior: 'smooth' });
});

// 导出报告
function exportReport() {
    const reportData = getReportData();
    let reportContent = '';
    
    // 根据报告类型生成内容
    if (currentReportType === 'daily') {
        reportContent = generateDailyReport(reportData);
    } else if (currentReportType === 'weekly') {
        reportContent = generateWeeklyReport(reportData);
    } else if (currentReportType === 'monthly') {
        reportContent = generateMonthlyReport(reportData);
    }
    
    // 发送到主进程导出
    ipcRenderer.send('export-report', {
        content: reportContent,
        reportType: currentReportType
    });
}

// 获取表单数据
function getReportData() {
    return {
        name: document.getElementById('report-name').value,
        department: document.getElementById('report-department').value,
        position: document.getElementById('report-position').value,
        status: document.getElementById('report-status').value,
        date: document.getElementById('report-date').value,
        startDate: document.getElementById('report-start-date').value,
        endDate: document.getElementById('report-end-date').value,
        summary: document.getElementById('report-summary').value,
        tasks: document.getElementById('report-tasks').value,
        achievements: document.getElementById('report-achievements').value,
        plans: document.getElementById('report-plans').value,
        issues: document.getElementById('report-issues').value,
        assistance: document.getElementById('report-assistance').value,
        notes: document.getElementById('report-notes').value
    };
}

// 生成日报
function generateDailyReport(data) {
    const date = data.date ? new Date(data.date).toLocaleDateString('zh-CN') : new Date().toLocaleDateString('zh-CN');
    
    return `# ${date} 日报

## 个人信息
- 姓名: ${data.name || '未填写'}
- 部门: ${data.department || '未填写'}
- 职位: ${data.position || '未填写'}

## 工位状态
- 今日状态: ${data.status || '未填写'}

## 今日工作内容
${data.tasks || '无'}

## 明日计划
${data.plans || '无'}

## 遇到的问题
${data.issues || '无'}

## 备注
${data.notes || '无'}`;
}

// 生成周报
function generateWeeklyReport(data) {
    const startDate = data.startDate ? new Date(data.startDate).toLocaleDateString('zh-CN') : '';
    const endDate = data.endDate ? new Date(data.endDate).toLocaleDateString('zh-CN') : new Date().toLocaleDateString('zh-CN');
    
    return `# ${startDate} 至 ${endDate} 周报

## 个人信息
- 姓名: ${data.name || '未填写'}
- 部门: ${data.department || '未填写'}
- 职位: ${data.position || '未填写'}

## 本周工作概述
${data.summary || '无'}

## 详细工作内容
${data.tasks || '无'}

## 下周计划
${data.plans || '无'}

## 遇到的问题及解决方案
${data.issues || '无'}

## 需要协助的事项
${data.assistance || '无'}

## 备注
${data.notes || '无'}`;
}

// 生成月报
function generateMonthlyReport(data) {
    const date = new Date();
    const month = `${date.getFullYear()}年${date.getMonth() + 1}月`;
    
    return `# ${month} 月报

## 个人信息
- 姓名: ${data.name || '未填写'}
- 部门: ${data.department || '未填写'}
- 职位: ${data.position || '未填写'}

## 本月工作概述
${data.summary || '无'}

## 主要工作成果
${data.achievements || '无'}

## 详细工作内容
${data.tasks || '无'}

## 下月计划
${data.plans || '无'}

## 遇到的问题及解决方案
${data.issues || '无'}

## 需要协助的事项
${data.assistance || '无'}

## 备注
${data.notes || '无'}`;
}

// 导出为文本
exportTextBtn.addEventListener('click', () => {
    const reportData = getReportData();
    let reportContent = '';
    let filename = '';
    
    if (currentReportType === 'daily') {
        reportContent = generateDailyReport(reportData);
        filename = `日报_${new Date().toLocaleDateString('zh-CN')}.txt`;
    } else if (currentReportType === 'weekly') {
        reportContent = generateWeeklyReport(reportData);
        filename = `周报_${new Date().toLocaleDateString('zh-CN')}.txt`;
    } else if (currentReportType === 'monthly') {
        reportContent = generateMonthlyReport(reportData);
        filename = `月报_${new Date().toLocaleDateString('zh-CN')}.txt`;
    }
    
    // 发送导出请求到主进程
    ipcRenderer.send('export-report-as-text', { content: reportContent, filename });
});

// 导出为Markdown
exportMdBtn.addEventListener('click', () => {
    const reportData = getReportData();
    let reportContent = '';
    let filename = '';
    
    if (currentReportType === 'daily') {
        reportContent = generateDailyReport(reportData);
        filename = `日报_${new Date().toLocaleDateString('zh-CN')}.md`;
    } else if (currentReportType === 'weekly') {
        reportContent = generateWeeklyReport(reportData);
        filename = `周报_${new Date().toLocaleDateString('zh-CN')}.md`;
    } else if (currentReportType === 'monthly') {
        reportContent = generateMonthlyReport(reportData);
        filename = `月报_${new Date().toLocaleDateString('zh-CN')}.md`;
    }
    
    // 发送导出请求到主进程
    ipcRenderer.send('export-report-as-md', { content: reportContent, filename });
});

// 复制到剪贴板
copyReportBtn.addEventListener('click', () => {
    const reportData = getReportData();
    let reportContent = '';
    
    if (currentReportType === 'daily') {
        reportContent = generateDailyReport(reportData);
    } else if (currentReportType === 'weekly') {
        reportContent = generateWeeklyReport(reportData);
    } else if (currentReportType === 'monthly') {
        reportContent = generateMonthlyReport(reportData);
    }
    
    // 复制到剪贴板
    navigator.clipboard.writeText(reportContent).then(() => {
        alert('报告内容已复制到剪贴板');
    }).catch(err => {
        console.error('复制失败:', err);
        alert('复制失败，请手动复制');
    });
});

// 关闭预览
closePreviewBtn.addEventListener('click', () => {
    reportPreview.style.display = 'none';
});

// 关闭窗口
closeReportBtn.addEventListener('click', () => {
    ipcRenderer.send('close-report-generator');
});